package com.levi.rabbitmq.direct;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * Direct 模式交换机的   消费者   分别接收error,info,waring三种routingkey的消息
 */
public class DirectConsumer1 {

    public static final String EXCHANGE_NAME = "direct";

    public static void main(String[] args) throws IOException, TimeoutException {
        //创建连接工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();
        //设置rabbitmq地址
        connectionFactory.setHost("127.0.0.1");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("admin");
        connectionFactory.setPassword("admin");
        //建立连接
        Connection connection = connectionFactory.newConnection();
        //获得信道
        Channel channel = connection.createChannel();

        //设置交换机模式为fanout广播模式
        channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.DIRECT);
        //设置一个非持久化的临时队列
        String queue = channel.queueDeclare().getQueue();
        //队列和交换机绑定  三个不同的routingkey
        channel.queueBind(queue, EXCHANGE_NAME, "error");
        channel.queueBind(queue, EXCHANGE_NAME, "waring");
        channel.queueBind(queue, EXCHANGE_NAME, "info");

        //接收消息                              自动确认
        Consumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
//                super.handleDelivery(consumerTag, envelope, properties, body);
                String message = new String(body, "UTF-8");
                System.out.println("收到了消息: " + message);
            }
        };
        channel.basicConsume(queue, true, consumer);
    }

}
